home *** CD-ROM | disk | FTP | other *** search
/ Czech Logic, Card & Gambling Games / Logické hry.iso / hry / Robocode / robocode-setup-1.0.7.jar / extract.jar / robots / sample / SittingDuck.java < prev    next >
Encoding:
Java Source  |  2005-02-18  |  1.9 KB  |  68 lines

  1. package sample;
  2. import robocode.*;
  3. import java.io.*;
  4. import java.awt.Color;
  5.  
  6. /**
  7.  * SittingDuck - a sample robot by Mathew Nelson
  8.  *
  9.  * Along with sitting still doing nothing,
  10.  * this robot demonstrates persistency.
  11.  */
  12. public class SittingDuck extends AdvancedRobot
  13. {
  14.     static boolean incrementedBattles = false;
  15.     
  16.     public void run() {
  17.         
  18.         setColors(Color.yellow,null,null);
  19.         
  20.         int roundCount, battleCount;
  21.         
  22.         // Read file "count.dat" which contains 2 lines,
  23.         // a round count, and a battle count
  24.         try {
  25.             BufferedReader r = new BufferedReader(new FileReader(getDataFile("count.dat")));
  26.             // Try to get the counts
  27.             roundCount = Integer.parseInt(r.readLine());
  28.             battleCount = Integer.parseInt(r.readLine());
  29.         } catch (IOException e) {
  30.             // Something went wrong reading the file, reset to 0.
  31.             roundCount = 0;
  32.             battleCount = 0;
  33.         } catch (NumberFormatException e) {
  34.             // Something went wrong converting to ints, reset to 0
  35.             roundCount = 0;
  36.             battleCount = 0;
  37.         }
  38.         
  39.         // Increment the # of rounds
  40.         roundCount++;
  41.         // If we havenn't incremented # of battles already,
  42.         // (Note:  Because robots are only instantiated once per battle,
  43.         //         member variables remain valid throughout it.
  44.         if (!incrementedBattles)
  45.         {
  46.             // Increment # of battles
  47.             battleCount++;
  48.             incrementedBattles = true;
  49.         }
  50.         
  51.         try {
  52.             PrintStream w = new PrintStream(new RobocodeFileOutputStream(getDataFile("count.dat")));
  53.             w.println(roundCount);
  54.             w.println(battleCount);
  55.             // PrintStreams don't throw IOExceptions during prints,
  56.             // they simply set a flag.... so check it here.
  57.             if (w.checkError())
  58.                 out.println("I could not write the count!");
  59.             w.close();
  60.         } catch (IOException e) {
  61.             out.println("IOException trying to write: " + e);
  62.         }
  63.  
  64.         out.println("I have been a sitting duck for " + roundCount + " rounds, in " + battleCount + " battles.");
  65.         
  66.     }
  67.  
  68. }